package cn.edu.baiyunu.myapplication.ui.history

import android.content.Intent
import android.net.Uri
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import cn.edu.baiyunu.myapplication.data.db.entity.PhotoRecord
import cn.edu.baiyunu.myapplication.ui.components.BottomNavigationBar
import cn.edu.baiyunu.myapplication.ui.components.PatternDotsBackground
import cn.edu.baiyunu.myapplication.ui.history.components.DeleteConfirmDialog
import cn.edu.baiyunu.myapplication.ui.history.components.EmptyHistoryContent
import cn.edu.baiyunu.myapplication.ui.history.components.FilterDialog
import cn.edu.baiyunu.myapplication.ui.history.components.HistoryTopBar
import cn.edu.baiyunu.myapplication.ui.history.components.PhotoItem
import java.io.File

/**
 * 历史页面主屏幕
 */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun HistoryScreen(
    viewModel: HistoryViewModel,
    onNavigateToUpload: () -> Unit,
    onNavigateToEdit: (PhotoRecord) -> Unit,
    onNavigateToHome: () -> Unit,
    onNavigateToSpecs: () -> Unit = {},
    onOpenSavedFolder: () -> Unit = {},
    modifier: Modifier = Modifier
) {
    val context = LocalContext.current
    val photoRecords by viewModel.photoRecords.observeAsState(emptyList())
    val searchQuery by viewModel.searchQuery.collectAsState()
    val isSearchVisible by viewModel.isSearchVisible.observeAsState(false)
    val sortOrder by viewModel.sortOrder.collectAsState()
    val selectedSpecType by viewModel.selectedSpecType.collectAsState()
    val statusMessage by viewModel.statusMessage.observeAsState()
    
    // 分组和排序后的照片
    val groupedPhotos = viewModel.getGroupedPhotoRecords(photoRecords)
    
    // 状态
    val snackbarHostState = remember { SnackbarHostState() }
    var showFilterDialog by remember { mutableStateOf(false) }
    var showDeleteAllDialog by remember { mutableStateOf(false) }
    var photoToDelete by remember { mutableStateOf<Long?>(null) }

    // 显示状态消息
    LaunchedEffect(statusMessage) {
        statusMessage?.let {
            snackbarHostState.showSnackbar(it)
            viewModel.clearStatusMessage()
        }
    }
    
    // 删除确认对话框
    if (photoToDelete != null) {
        DeleteConfirmDialog(
            title = "删除照片",
            message = "确认删除此照片？此操作无法撤销。",
            onConfirm = {
                photoToDelete?.let { viewModel.deletePhotoRecord(it) }
                photoToDelete = null
            },
            onDismiss = {
                photoToDelete = null
            }
        )
    }
    
    // 删除所有确认对话框
    if (showDeleteAllDialog) {
        DeleteConfirmDialog(
            title = "清空历史记录",
            message = "确认删除所有历史照片？此操作无法撤销。",
            onConfirm = {
                viewModel.clearAllPhotoRecords()
                showDeleteAllDialog = false
            },
            onDismiss = {
                showDeleteAllDialog = false
            }
        )
    }
    
    // 筛选对话框
    if (showFilterDialog) {
        FilterDialog(
            selectedSpecType = selectedSpecType,
            onSpecTypeSelected = viewModel::setSelectedSpecType,
            onDismiss = { showFilterDialog = false }
        )
    }

    Box(
        modifier = modifier
            .fillMaxSize()
            .background(Color(0xFFF8FAFC))
    ) {
        // 绘制背景图案
        PatternDotsBackground()
        
        Scaffold(
            topBar = {
                HistoryTopBar(
                    title = "照片记录",
                    isSearchVisible = isSearchVisible,
                    searchQuery = searchQuery,
                    onQueryChange = viewModel::updateSearchQuery,
                    onSearchClick = { viewModel.setSearchVisible(true) },
                    onClearSearch = { viewModel.setSearchVisible(false) },
                    onFilterClick = { showFilterDialog = true },
                    onSortClick = viewModel::toggleSortOrder,
                    onDeleteAllClick = { showDeleteAllDialog = true },
                    sortOrder = sortOrder,
                    onOpenFolderClick = onOpenSavedFolder
                )
            },
            snackbarHost = { SnackbarHost(snackbarHostState) },
            containerColor = Color.Transparent
        ) { paddingValues ->
            // 主内容
            if (photoRecords.isEmpty()) {
                // 无历史记录时显示空状态
                EmptyHistoryContent(
                    onCreateClick = onNavigateToUpload,
                    modifier = Modifier.padding(paddingValues)
                )
            } else {
                // 有历史记录时显示列表
                LazyColumn(
                    contentPadding = PaddingValues(
                        top = paddingValues.calculateTopPadding() + 4.dp,
                        bottom = paddingValues.calculateBottomPadding() + 16.dp
                    )
                ) {
                    // 按日期分组显示
                    groupedPhotos.forEach { (date, photos) ->
                        // 日期标题
                        item {
                            Column(
                                modifier = Modifier.padding(
                                    start = 16.dp, 
                                    end = 16.dp, 
                                    top = 16.dp, 
                                    bottom = 8.dp
                                )
                            ) {
                                Text(
                                    text = date,
                                    fontSize = 16.sp,
                                    fontWeight = FontWeight.Bold,
                                    color = Color(0xFF334155)
                                )
                                
                                Spacer(modifier = Modifier.height(4.dp))
                            }
                        }
                        
                        // 照片列表
                        items(photos) { photo ->
                            PhotoItem(
                                photoRecord = photo,
                                formattedDate = viewModel.getFormattedDate(photo.createdAt),
                                onPhotoClick = onNavigateToEdit,
                                onEditClick = onNavigateToEdit,
                                onDeleteClick = { photoToDelete = it },
                                onShareClick = { sharePhoto(context, it) }
                            )
                        }
                    }
                }
            }
        }
    }
}

/**
 * 分享照片
 */
private fun sharePhoto(context: android.content.Context, photoRecord: PhotoRecord) {
    val file = File(photoRecord.filePath)
    if (file.exists()) {
        val uri = Uri.fromFile(file)
        val shareIntent = Intent().apply {
            action = Intent.ACTION_SEND
            putExtra(Intent.EXTRA_STREAM, uri)
            type = "image/*"
        }
        context.startActivity(Intent.createChooser(shareIntent, "分享照片"))
    }
} 